package com.hm.uums.service;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hm.common.utils.DateUtils;
import com.hm.common.utils.StringUtils;
import com.hm.uums.mapper.FunctionMapper;

/**
 * @author hwg
 *
 *         2020年12月18日
 */
@Service
public class FunctionService {

	@Autowired
	private FunctionMapper functionMapper;

	public Map<String, Object> getFunction(BigInteger functionId) {
		return functionMapper.getFunction(functionId);
	}

	@Transactional
	public void addFunction(Map<String, Object> dMap) {
		if (StringUtils.isNotEmpty(dMap.get("functionPId"))) {
			Map<String, Object> pFunctionMap = this.getFunction((BigInteger) dMap.get("functionPId"));
			dMap.put("fullPId", StringUtils.ifEmptyReturn(pFunctionMap.get("fullPId"), "") + "-" + dMap.get("functionPId"));
		}

		dMap.put("createtime", DateUtils.fnow());
		dMap.put("updatetime", DateUtils.fnow());
		functionMapper.addFunction(dMap);
	}

	@Transactional
	public void editFunction(Map<String, Object> dMap) {
		BigInteger functionId = (BigInteger) dMap.get("functionId");
		BigInteger functionPId = (BigInteger) dMap.get("functionPId");

		//如果有上级，则设置fullPId
		if (StringUtils.isNotEmpty(functionPId)) {
			Map<String, Object> pFunctionMap = this.getFunction(functionPId);
			dMap.put("fullPId", StringUtils.ifEmptyReturn(pFunctionMap.get("fullPId"), "") + "-" + functionPId.longValue());
		}

		//先获取未修改的数据
		Map<String, Object> functionMap = this.getFunction(functionId);

		dMap.put("updatetime", DateUtils.fnow());
		functionMapper.editFunction(dMap);

		// 如果当前节点没有子节点，就返回
		if (functionMapper.hasSubFunction(functionId) == 0) {
			return;
		}

		String oldSubFullPId = StringUtils.ifEmptyReturn(functionMap.get("fullPId"), "") + "-" + functionId.toString();
		String newSubFullPId = StringUtils.ifEmptyReturn(dMap.get("fullPId"), "") + "-" + functionId.toString();

		//如果上级节点没有变化，就不需要修改子节点，返回
		if (oldSubFullPId.equals(newSubFullPId)) {
			return;
		}

		//修改当前节点下的所以子节点fullPId
		functionMapper.editSubFullPId(newSubFullPId, oldSubFullPId, (String) dMap.get("updatetime"));
	}

	@Transactional
	public int editFunctionStatus(BigInteger functionId, int status) {
		if (status == 1) {//禁用的情况下，验证是否存在子机构未禁用
			long hasEnableSubFunction = functionMapper.hasEnableSubFunction(functionId);
			if (hasEnableSubFunction > 0) {
				return 1;
			}
		}
		functionMapper.editFunctionStatus(functionId, status, DateUtils.fnow());
		return 0;
	}

	@Transactional
	public int delFunction(BigInteger functionId) {
		long hasSubFunction = functionMapper.hasSubFunction(functionId);
		if (hasSubFunction > 0) {
			return 1;
		}
		functionMapper.delFunction(functionId);
		return 0;
	}

	public List<Map<String, Object>> list(Map<String, Object> params) {
		return functionMapper.list(params);
	}

}
